package controllers

import (
	"encoding/json"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"goods-master/cache"
	"goods-master/models"
	"time"
)

type GoodsController struct {
	beego.Controller
}
type Res struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *GoodsController) Add() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	id, _ := c.GetInt("id")
	name := c.GetString("name")
	emil := c.GetString("emil")
	price, _ := c.GetFloat("price")
	good := models.Goods{
		Id:    id,
		Name:  name,
		Emil:  emil,
		Price: price,
	}
	err := models.DB.Create(&good).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
}
func (c *GoodsController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	var good []models.Goods
	err := models.DB.Find(&good).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		key := fmt.Sprintf("good_list_%d", models.Goods{}.Id)
		res, _ := cache.Rdb.Get(cache.Ctx, key).Result()
		if res != "" {
			json.Unmarshal([]byte(res), good)
		} else {
			rest, _ := json.Marshal(good)
			cache.Rdb.Set(cache.Ctx, key, rest, time.Hour*2)
		}
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "查询成功",
			Data: good,
		}
		c.ServeJSON()
		return
	}
}
func (c *GoodsController) Up() {
	id, _ := c.GetInt("id")
	name := c.GetString("name")
	emil := c.GetString("emil")
	price, _ := c.GetFloat("price")
	good := models.Goods{
		Id:    id,
		Name:  name,
		Emil:  emil,
		Price: price,
	}
	err := models.DB.Where("id=?", id).Updates(&good).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		key := fmt.Sprintf("good_up_%d", models.Goods{}.Id)
		res, _ := cache.Rdb.Get(cache.Ctx, key).Result()
		if res != "" {
			json.Unmarshal([]byte(res), id)
		} else {
			rest, _ := json.Marshal(id)
			cache.Rdb.Set(cache.Ctx, key, rest, time.Hour*2)
		}
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "修改成功",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
}
func (c *GoodsController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.Goods{}, id).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		key := fmt.Sprintf("good_del_%d", models.Goods{}.Id)
		res, _ := cache.Rdb.Get(cache.Ctx, key).Result()
		if res != "" {
			json.Unmarshal([]byte(res), id)
		} else {
			rest, _ := json.Marshal(id)
			cache.Rdb.Set(cache.Ctx, key, rest, time.Hour*2)
		}
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
}
